'use client'

import { useState, useEffect } from 'react'
import Image from 'next/image'
import Link from 'next/link'
import { useParams } from 'next/navigation'
import { API_CONFIG } from '../../config'

interface Product {
  id: number
  name: string
  image: string
  price: string
  description: string
  stock: number
  status: string
  category_id: number
  create_time: string
  update_time: string
  is_home: number
}

export default function ProductDetail() {
  const params = useParams()
  const [quantity, setQuantity] = useState(1)
  const [product, setProduct] = useState<Product | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const fetchProduct = async () => {
      try {
        const response = await fetch('/api/goodsinfo', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ id: params.id }),
        })
        const data = await response.json()
        setProduct(data)
      } catch (error) {
        console.error('Error fetching product:', error)
      } finally {
        setLoading(false)
      }
    }

    fetchProduct()
  }, [params.id])

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-2xl font-bold mb-4">Loading...</h1>
        </div>
      </div>
    )
  }

  if (!product) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-2xl font-bold mb-4">Product Not Found</h1>
          <Link href="/shop" className="text-primary hover:underline">
            Back to Shop
          </Link>
        </div>
      </div>
    )
  }

  const handleQuantityChange = (delta: number) => {
    setQuantity(prev => Math.max(1, Math.min(prev + delta, product.stock)))
  }

  const addToCart = () => {
    try {
      // 1. 获取现有购物车数据
      const existingCart = localStorage.getItem('cart');
      const cart = existingCart ? JSON.parse(existingCart) : [];

      // 2. 检查商品是否已在购物车中
      const existingItemIndex = cart.findIndex((item:any) => item.id === product.id);

      if (existingItemIndex >= 0) {
        // 如果商品已存在，增加数量
        cart[existingItemIndex].quantity += quantity;
      } else {
        // 如果商品不存在，添加新商品
        cart.push({
          id: product.id,
          name: product.name,
          price: product.price,
          image: product.image,
          quantity: quantity
        });
      }

      // 3. 保存更新后的购物车数据
      localStorage.setItem('cart', JSON.stringify(cart));

      // 4. 显示成功提示
      alert('Added to cart successfully!');
    } catch (error) {
      console.error('Error adding to cart:', error);
      alert('Failed to add to cart');
    }
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="container py-16">
        <div className="mb-8">
          <Link href="/shop" className="text-primary hover:underline flex items-center">
            <svg className="w-4 h-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
            </svg>
            Back to Products
          </Link>
        </div>

        <div className="bg-white rounded-lg shadow-sm overflow-hidden">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-8 p-8">
            {/* Product Image */}
            <div className="relative aspect-square">
              <Image
                src={`${API_CONFIG.BASE_URL}${product.image}`}
                alt={product.name}
                fill
                className="object-cover rounded-lg"
              />
            </div>

            {/* Product Info */}
            <div>
              <div className="mb-6">
                <h1 className="text-3xl font-bold mb-2">{product.name}</h1>
                <p className="text-gray-600 mb-4">{product.description}</p>
                <div className="text-3xl font-bold text-primary mb-6">
                  ${product.price}
                </div>
              </div>

              <div className="mb-6">
                <h2 className="font-semibold mb-2">Stock Status</h2>
                <p className="text-gray-600">{product.stock} units available</p>
              </div>

              <div className="mb-8">
                <h2 className="font-semibold mb-4">Quantity</h2>
                <div className="flex items-center space-x-4">
                  <div className="flex items-center border rounded">
                    <button
                      onClick={() => handleQuantityChange(-1)}
                      className="px-4 py-2 hover:bg-gray-100"
                    >
                      -
                    </button>
                    <span className="px-4 py-2 border-x">{quantity}</span>
                    <button
                      onClick={() => handleQuantityChange(1)}
                      className="px-4 py-2 hover:bg-gray-100"
                    >
                      +
                    </button>
                  </div>
                </div>
              </div>

              <button
                onClick={addToCart}
                className="inline-block bg-[#ff4d8c] text-white px-6 py-2 rounded hover:bg-[#ff3377] transition-colors w-full mt-6"
              >
                Add to Cart
              </button>
            </div>
          </div>
        </div>

        {/* Warning Notice */}
        <div className="mt-16 text-center text-gray-500">
          <p className="text-sm">WARNING: This product contains nicotine. Nicotine is an addictive chemical.</p>
        </div>
      </div>
    </div>
  )
}